package com.cyw.common.utils;

import java.util.Random;

/**
 * 生成随机数
 */
public class CodeUtils {


    public static String randomNumberCode(int length) {
        return length <= 0 ? "" :
                length > 9 ? randomBigNumberCode(length) : randomNumberCode(length, new Random());
    }

    private static String randomNumberCode(int length, Random random) {
        int max = (int) Math.pow(10, length);
        int num = random.nextInt(max);
        return String.format("%0" + length + "d", num);
    }

    /**
     * 长度大于9时执行，防溢出
     *
     * @param length 要返回的字符串的长度
     * @return 随机字符串
     */
    private static String randomBigNumberCode(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        do {
            sb.append(randomNumberCode(9, random));
        } while ((length -= 9) > 9);
        sb.append(randomNumberCode(length, random));
        return sb.toString();
    }

    public static String randomStringCode(int num) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return randomString(base, num);
    }

    public static String randomReadableStringCode(int num) {
        String base = "abcdefghjkmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY3456789";
        return randomString(base, num);
    }

    private static String randomString(String base, int num) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
